package com.gp.billsrecord.ui.common

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.gp.billsrecord.R
import com.gp.billsrecord.databinding.FragmentAccountAddBinding
import com.gp.billsrecord.model.data.AccountType
import com.gp.billsrecord.ui.common.adapters.AccountSpinnerAdapter
import com.gp.billsrecord.vm.AppViewModel
import com.xujichang.base.extensions.Logs
import com.xujichang.base.extensions.postToast
import kotlinx.coroutines.launch
import java.lang.RuntimeException

/**
 * 添加账户
 */
class AccountAddDialog : BottomSheetDialogFragment() {
    private val spinnerAdapter by lazy {
        AccountSpinnerAdapter(requireContext(), R.layout.item_spinner, R.id.tv_account_type_name)
    }
    private val viewModel by viewModels<AppViewModel>()

    private var _binding: FragmentAccountAddBinding? = null
    private val binding: FragmentAccountAddBinding get() = _binding ?: throw RuntimeException("")

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        //关联xml的view文件
        return FragmentAccountAddBinding.inflate(inflater, container, false).also {
            _binding = it
            initBinding()
        }.root
    }

    private fun initBinding() {
        //初始化账户类型选择器
        binding.spinnerAccountType.also { spinner ->
            spinner.adapter = spinnerAdapter
        }
        //保存账户按钮
        binding.btnAccountSave.setOnClickListener {
            //spinner 选中的index
            val position = binding.spinnerAccountType.selectedItemPosition
            //根据Index获取具体的账户类型
            val accountType = if (position == -1) {
                null
            } else spinnerAdapter.getItem(position)
            //
            accountType?.also {
                val number = binding.etAccountNumber.text.toString()
                val balance = binding.etAccountBalance.text.toString()
                val realBalance = balance.toDouble().times(100).toLong()

                viewModel.addAccount(number, realBalance, accountType)
                    .observe(viewLifecycleOwner) {
                        if (it) {
                            postToast("添加成功")
                            dismiss()
                        } else
                            postToast("添加失败")
                    }
            } ?: postToast("未选择账户类型")
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        //获取并监听数据库中的账户类型
        viewModel.observeAccountTypes().observe(viewLifecycleOwner) {
            //初始化Spinner
            initSpinner(it)
        }
    }

    /**
     * 更新账户类型spinner得数据
     */
    private fun initSpinner(list: List<AccountType>) {
        spinnerAdapter.clear()
        spinnerAdapter.addAll(list)
    }

    companion object {
        const val TAG = "AccountAddDialog"
    }
}